package com.roc.web.action.terminal;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblTermInf;
import com.roc.pojo.YjPosInfo;
import com.roc.service.IMerchantServices;
import com.roc.service.IPagenitionService;
import com.roc.service.ITerminalService;
import com.roc.service.IorgService;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.util.Constance;
import com.roc.util.constant.ConfigMerinfoUtil;
import com.roc.util.constant.ConfigProperties;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

/**
 * 
 * @author 陈锴
 * 
 *         终端序列号添加
 * 
 *         2014-08-18
 *
 */

@Component
@Scope("prototype")
@Namespace("/termAgentSn")
public class TermSnAgentAction extends PaginationBaseAction {

	private Logger logger = LogManager.getLogger(TermSnAgentAction.class);

	private TermSnAgentSearchCondition searchCondition;
	private TblTermInf termInfos = new TblTermInf();
	private TblMchtInf tblMchtInf;
	private YjPosInfo yjPos;
	private String tid;
	private String mid;
	private String serialNumer;
	private String posBrandCode;// 厂商编号
	private String serNums;
	private String brandno;
	private Map<String, String> brandMap;
	private String oldSerialNumber;
	private String bindFlag;// 绑定标志
	private String invaild;// 失效标志
	private String dealFlag;//1解绑标志，2解绑成功，3冻结标志，4解冻标志
	private String nowserialNum;
	private String msg;//应答信息
	private String remark;//备注
	@Autowired
	IorgService orgService;

	@Autowired
	IPageService pagenitionService;

	@Autowired
	ITerminalService terminalService;

	@Autowired
	IMerchantServices merchantServices;
	
	@Autowired
	IPowerInfoService powerInfoService;
	/**
	 * 终端绑定初始化
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "termSnAgentInit", results = { @Result(name = "success", location = "/pages/terminal/termSnAgentInfoRepeatBind.jsp") })
	public String termSnInfoAction() throws Exception {
		org();
		searchCondition = new TermSnAgentSearchCondition();
		searchCondition.setTid(tid);
		searchCondition.setMid(mid);
		return SUCCESS;
	}
	/**
	 * 初始化参数
	 */
	private void org() {
		try {
			getRequest().setAttribute("brandMap",
					ConfigProperties.getSysDB1("TMNL_BRAND", true));
			getRequest().setAttribute("nameMap", "");
			getRequest().setAttribute("typeMap",
					ConfigProperties.getSysDB1("Terminal_Type", true));
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/**
	 * 查询待绑定的SN序列号
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "terminalSnAgentList", results = { @Result(name = "success", location = "/pages/terminal/termSnAgentInfoRepeatBind.jsp") })
	public String terminalSnAgentList() throws Exception {
		Operators loginOperator = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);

		if (searchCondition == null) {
			searchCondition = (TermSnAgentSearchCondition) getSearchConditionFromSession();
			if (searchCondition == null) {
				searchCondition = new TermSnAgentSearchCondition();
			}
		}
		try {
			org();
			long agentId = loginOperator.getId();			
			if(Role.OPERATORS_COMM.getCode().equals(loginOperator.getRoleType()) || Role.OPERATORS_LEAD.getCode().equals(loginOperator.getRoleType())){
				agentId = loginOperator.getSuperiorId();
			}
			searchCondition.setAgentId(agentId);

			int rows = pagenitionService.countSQL(searchCondition);
			List<YjPosInfo> posList = new ArrayList<YjPosInfo>();
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);//
				if (searchRsList != null && searchRsList.size() > 0) {
					YjPosInfo pos = null;
					Iterator iterator = searchRsList.iterator();
					BigDecimal value = null;
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();
						pos = new YjPosInfo();
						pos.setSerialNum(Constance.Null2EmptyTrim(obj[0]));

						pos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(Constance
								.Null2EmptyTrim(obj[1])));
						pos.setPosType(ConfigMerinfoUtil.getPosType(Constance
								.Null2EmptyTrim(obj[2])));
						// pos.setPosName(Constance.Null2EmptyTrim(obj[3]));
						pos.setPosName(ConfigMerinfoUtil.getPosMODEL(
								Constance.Null2EmptyTrim(obj[3]),
								Constance.Null2EmptyTrim(obj[1])));

						value = (BigDecimal) obj[4];
						pos.setAgentId(value.longValue());
						pos.setIsUsed(convertConstantValue(Constance
								.Null2EmptyTrim(obj[5])));
						// pos.setIsUsed(Constance.Null2EmptyTrim(obj[5]));
						pos.setDtCreate((Date) obj[6]);
						pos.setDtLostmod((Date) obj[7]);
						// 厂商编号
						pos.setPosBrandCode(Constance.Null2EmptyTrim(obj[1]));
						posList.add(pos);
					}
				}
			}
			searchRsList.clear();
			searchRsList.addAll(posList);
			dealWithTheListSpecially(searchRsList);
			getRequest().setAttribute("posList", posList);
			getRequest().setAttribute("selModelCode",
					searchCondition.getPosName());
			getRequest().setAttribute("oldBandCode",
					searchCondition.getPosBrand());
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);

		} catch (ServiceException e) {

			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());

		}
		return SUCCESS;
	}

	/**
	 * 终端绑定操作
	 * 
	 * @return
	 */
	@Action(value = "terminalSnAgentSelect", results = { @Result(name = "success", type = "json") })
	public String selectSerialNum() {
		Operators currentOpr = (Operators) ActionContext.getContext()
				.getSession().get(Constant.SESSION_LOGIN_MERCHANT);		
		try {
			if (Constance.isEmpty(mid) || Constance.isEmpty(tid)
					|| Constance.isEmpty(serialNumer)
					|| Constance.isEmpty(posBrandCode)) {
				invaild = "error";
				return SUCCESS;
			}
			Operators loginOperator=null;
			if(Role.OPERATORS_COMM.getCode().equals(currentOpr.getRoleType()) || Role.OPERATORS_LEAD.getCode().equals(currentOpr.getRoleType())){
				loginOperator=powerInfoService.loadOperatorsById(currentOpr.getSuperiorId());
			}else{
				loginOperator=currentOpr;
			}
			// 防止多人同时操作同一终端绑定重复SN(修复)
			String num = terminalService.bindTerminal(mid, tid, serialNumer,
					posBrandCode,currentOpr,loginOperator);
			if (num != null) {
				bindFlag = "Exist";
				oldSerialNumber = num;
			}
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}

	// 解绑/冻结解冻页面初始化
	@Action(value = "terminalSnUnbundInit", results = { @Result(name = "success", location = "/pages/terminal/terminal_sn_unbund.jsp")})
	public String terminalSnUnbundInit() throws Exception {
		try {
			tblMchtInf = merchantServices.queryMerchat(mid);
			termInfos = terminalService.queryTermInfopart(tid, mid);
			yjPos = terminalService.queryYjPosInfo(termInfos.getDeviceCd(),
					termInfos.getTmnlBrand());
			if (yjPos != null) {
				yjPos.setPosBrandCode(yjPos.getPosBrand());
				yjPos.setPosName(ConfigMerinfoUtil.getPosMODEL(
						yjPos.getPosName(), yjPos.getPosBrand()));
				yjPos.setPosBrand(ConfigMerinfoUtil.getPosBRAND(yjPos
						.getPosBrand()));
				yjPos.setPosType(ConfigMerinfoUtil.getPosType(yjPos
						.getPosType()));
			}
			getRequest().setAttribute("dealFlag", dealFlag);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}

		return SUCCESS;
	}

	/**
	 * 终端解绑
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "terminalSnUnbund", results = {
			@Result(name = "success", location = "/pages/terminal/terminal_sn_unbund.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String terminalSnUnbund() throws Exception {
		try {
			if (Constance.isEmpty(mid) || Constance.isEmpty(tid)
					|| Constance.isEmpty(nowserialNum)
					|| Constance.isEmpty(posBrandCode)) {
				addActionError("传递的参数值异常,请重新登录或者刷新页面!");
				return ERROR;
			}
			Operators logingMerchant = (Operators) getSession().getAttribute(
					Constant.SESSION_LOGIN_MERCHANT);
			terminalService.unbindTerminal(nowserialNum, posBrandCode, mid,
					tid, logingMerchant.getAccountNo());
			dealFlag = "2";//
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
		}

		return terminalSnUnbundInit();
	}

	/**
	 * 转换Y/N枚举字段为中文汉字枚举值
	 * 
	 * @param value
	 * @return
	 */
	private String convertConstantValue(String value) {
		String constantValue = "";
		if (value != null && !"".equals(value)) {
			if (value.equals("Y")) {
				constantValue = "是";
			} else if (value.equals("N")) {
				constantValue = "否";
			}
		}
		return constantValue;
	}

	@Override
	protected String getInitPageSize() {
		// TODO Auto-generated method stub
		return Constance.PAGE_MAX_SIZE + "";
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSession()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		// TODO Auto-generated method stub
		return (TermSnAgentSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_BEAN_TERM_SN_AGENT);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.roc.page.PaginationBaseAction#getSearchConditionFromSubClass()
	 */
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		// TODO Auto-generated method stub
		return searchCondition;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchConditionToSubClass(com.roc
	 * .page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.roc.page.PaginationBaseAction#setSearchToConditionSession(com.roc
	 * .page.BaseSearchCondition)
	 */
	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_BEAN_TERM_SN_AGENT,
				searchCondition);
	}

	public TermSnAgentSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(TermSnAgentSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public String getTid() {
		return tid;
	}

	public void setTid(String tid) {
		this.tid = tid;
	}

	public String getMid() {
		return mid;
	}

	public void setMid(String mid) {
		this.mid = mid;
	}

	public String getSerialNumer() {
		return serialNumer;
	}

	public void setSerialNumer(String serialNumer) {
		this.serialNumer = serialNumer;
	}

	public String getSerNums() {
		return serNums;
	}

	public void setSerNums(String serNums) {
		this.serNums = serNums;
	}

	public String getPosBrandCode() {
		return posBrandCode;
	}

	public void setPosBrandCode(String posBrandCode) {
		this.posBrandCode = posBrandCode;
	}

	@Action(value = "terminalPosMODELSelect", results = { @Result(name = "success", type = "json", params = {
			"root", "brandMap" }) })
	public String selectPosMODEL() {
		brandMap = ConfigProperties.getSyspostype("TMNL_MODEL_NO", brandno,
				true);
		return SUCCESS;
	}

	public String getBrandno() {
		return brandno;
	}

	public void setBrandno(String brandno) {
		this.brandno = brandno;
	}

	public Map<String, String> getBrandMap() {
		return brandMap;
	}

	public void setBrandMap(Map<String, String> brandMap) {
		this.brandMap = brandMap;
	}

	public String getOldSerialNumber() {
		return oldSerialNumber;
	}

	public void setOldSerialNumber(String oldSerialNumber) {
		this.oldSerialNumber = oldSerialNumber;
	}

	public String getBindFlag() {
		return bindFlag;
	}

	public void setBindFlag(String bindFlag) {
		this.bindFlag = bindFlag;
	}

	public String getInvaild() {
		return invaild;
	}

	public void setInvaild(String invaild) {
		this.invaild = invaild;
	}

	public TblTermInf getTermInfos() {
		return termInfos;
	}

	public void setTermInfos(TblTermInf termInfos) {
		this.termInfos = termInfos;
	}

	public TblMchtInf getTblMchtInf() {
		return tblMchtInf;
	}

	public void setTblMchtInf(TblMchtInf tblMchtInf) {
		this.tblMchtInf = tblMchtInf;
	}

	public YjPosInfo getYjPos() {
		return yjPos;
	}

	public void setYjPos(YjPosInfo yjPos) {
		this.yjPos = yjPos;
	}

	public String getDealFlag() {
		return dealFlag;
	}

	public void setDealFlag(String dealFlag) {
		this.dealFlag = dealFlag;
	}

	public String getNowserialNum() {
		return nowserialNum;
	}

	public void setNowserialNum(String nowserialNum) {
		this.nowserialNum = nowserialNum;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	
}
